<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'

import httpInstance from "@/http";

const form = ref({
  name: "",
  file: '',
})
const fileList = ref([
  {
    name: "vue全家桶"
  }
])

//自定义上传，会传入一个v,v是一个对象，包含了文件和请求方法等数据
const uploadFile = (v) => {
  //缓存到form
  form.value.file = v.file;

}
const uploadExceed=()=>{
  ElMessage.warning("已超出最大文件数！")
}

const onPreview=()=>{
  ElMessage.warning("是否进行操作")
}

//校验类型以及大小
const beforeUpload=(file)=>{
  console.log(file);
  const isJpg=file.type === 'image/jpeg';
  const isValidSize=file.size/1024/1024 <2;
  if(!isJpg){
    ElMessage.warning("仅仅支持jpg格式文件");
    return false;
  }
  if(!isValidSize){
    ElMessage.warning("文件大小不能超过2M");
    return false;
  }
  return isJpg;
}
const onSubmit = async () => {
  //数据交互
  let formData = new FormData();
  formData.append('name', form.value.name); //值类型要value.name
  formData.append('file', form.value.file);
  //axios
  let data = await httpInstance.post('/systemFile/uploadSingleFile', formData, {
    //表单包含文件上传
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
  if (data.code === '20000')
    ElNotification({
      title: '消息',
      message: ('i', { style: 'color: teal' }, '文件上传成功'),
      duration:2000
    })
}
</script>


<template>

  <el-card style="max-width: 800px">
    <template #header>
      <div class="card-header">
        <span>单文件上传</span>
      </div>
    </template>

    <el-form :model="form" label-width="auto" style="max-width: 800px">
      <el-form-item label="文件名称">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="上传文件">
        <el-upload 
        v-model:file-list="fileList" 
        class="upload-demo" 
        action="" 
        :http-request="uploadFile" 
        limit="1"
        :on-exceed="uploadExceed"
        :before-upload="beforeUpload"
        :on-preview="onPreview"

        >
          <el-button type="primary">Click to upload</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500KB.
            </div>
          </template>
        </el-upload>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
      </el-form-item>

    </el-form>

  </el-card>



</template>


<style lang="scss" scoped></style>